<script setup lang="ts">
import { ref, computed } from 'vue';
import { useRestorationStore } from '../../stores/restorationStore';
import { formatFileSize } from '../../utils/fileUtils';
import imageRestorationService from '../../services/ImageRestorationService';

const restorationStore = useRestorationStore();
const selectedImageId = ref<string | null>(null);
const isDownloading = ref(false);
const downloadProgress = ref(0);

// 清空还原图片，保留上传的图片和元数据
function clearRestoredImages() {
  if (confirm('确定要清空所有还原的图片吗？')) {
    restorationStore.clearRestoredImages();
  }
}

// Compute total size of all restored images
const totalSize = computed(() => {
  // Estimate size based on dimensions and format
  return restorationStore.restoredImages.reduce((sum, img) => {
    const pixelCount = img.width * img.height;
    // Rough estimation: PNG ~= 4 bytes per pixel, JPEG ~= 0.25 bytes per pixel
    const bytesPerPixel = img.format === 'png' ? 4 : 0.25;
    return sum + (pixelCount * bytesPerPixel);
  }, 0);
});

function selectImage(id: string) {
  selectedImageId.value = selectedImageId.value === id ? null : id;
}

async function downloadImage(id: string) {
  const image = restorationStore.restoredImages.find(img => img.id === id);
  if (!image) {
    console.error('Image not found:', id);
    return;
  }

  try {
    // 使用RestorationStore中的方法，这样会应用用户设置的质量参数
    await restorationStore.downloadRestoredImage(image);
  } catch (error) {
    console.error('下载图片失败:', error);
    alert('下载图片失败，请重试');
  }
}

async function downloadAllAsZip() {
  if (restorationStore.restoredImages.length === 0) {
    return;
  }

  // Set downloading state
  isDownloading.value = true;
  downloadProgress.value = 0;

  try {
    // 使用RestorationStore中的方法，这样会应用用户设置的质量参数
    await restorationStore.downloadAsZip();

    // 监听下载进度
    const unwatch = restorationStore.$subscribe((mutation, state) => {
      if (mutation.type === 'direct' && 'downloadProgress' in mutation.payload) {
        downloadProgress.value = state.downloadProgress;
      }
    });

    // 下载完成后取消监听
    setTimeout(() => unwatch(), 1000);
  } catch (error) {
    console.error('下载ZIP文件失败:', error);
    alert('下载ZIP文件失败，请重试');
  } finally {
    // Reset downloading state
    isDownloading.value = false;
    downloadProgress.value = 0;
  }
}
</script>

<template>
  <div v-if="restorationStore.restoredImages.length > 0" class="restored-images-viewer">
    <div class="gallery-header">
      <h3>还原结果 ({{ restorationStore.restoredImages.length }})</h3>
      <div class="gallery-actions">
        <button @click="clearRestoredImages" class="clear-button" aria-label="清空还原图片">
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">
            <path fill="currentColor"
              d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z" />
          </svg>
          清空
        </button>
        <p>总大小: {{ formatFileSize(totalSize) }}</p>
      </div>
    </div>

    <div class="gallery-grid">
      <div v-for="image in restorationStore.restoredImages" :key="image.id" class="image-item"
        :class="{ selected: selectedImageId === image.id }" @click="selectImage(image.id)">
        <div class="image-preview">
          <img :src="image.url" :alt="image.name">
        </div>
        <div class="image-info">
          <p class="image-name">{{ image.name }}</p>
          <p class="image-details">
            {{ image.width }}x{{ image.height }}
          </p>
          <button class="download-button" @click.stop="downloadImage(image.id)" aria-label="下载图片" tabindex="0"
            @keydown.enter="downloadImage(image.id)">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" aria-hidden="true">
              <path fill="currentColor" d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z" />
            </svg>
            下载
          </button>
        </div>
      </div>
    </div>

    <div v-if="isDownloading" class="download-progress">
      <div class="progress-bar">
        <div class="progress-fill" :style="{ width: downloadProgress + '%' }"></div>
      </div>
      <p>下载中... {{ downloadProgress }}%</p>
    </div>

    <div class="download-all">
      <button @click="downloadAllAsZip" :disabled="isDownloading" aria-label="下载所有图片为ZIP压缩包" tabindex="0"
        @keydown.enter="downloadAllAsZip">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" aria-hidden="true">
          <path fill="currentColor" d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z" />
        </svg>
        下载所有图片 (ZIP)
      </button>
    </div>
  </div>
</template>

<style scoped>
.restored-images-viewer {
  margin-top: 2rem;
}

h3 {
  margin-bottom: 1rem;
}

.gallery-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 1rem;
  margin-bottom: 1.5rem;
}

/* Responsive styles */
@media (max-width: 576px) {
  .gallery-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 0.5rem;
  }
}

.image-item {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
  background-color: #fff;
}

.image-preview {
  height: 150px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
}

.image-preview img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.image-info {
  padding: 0.75rem;
}

.image-name {
  font-size: 0.9rem;
  margin: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.image-details {
  font-size: 0.8rem;
  color: #666;
  margin: 0.25rem 0 0.5rem 0;
}

.download-button {
  width: 100%;
  padding: 0.4rem;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
}

.download-button:hover {
  background-color: #45a049;
}

.download-all {
  text-align: center;
}

.download-all button {
  padding: 0.75rem 1.5rem;
  background-color: #2196f3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
}

.download-all button:hover {
  background-color: #0b7dda;
}

.download-all button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.download-all button {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
}

.download-button {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
}

.gallery-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.gallery-actions {
  display: flex;
  align-items: center;
  gap: 1rem;
  font-size: 0.9rem;
  color: #666;
}

.clear-button {
  display: flex;
  align-items: center;
  gap: 0.3rem;
  padding: 0.4rem 0.8rem;
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
}

.clear-button:hover {
  background-color: #d32f2f;
}

.image-item {
  cursor: pointer;
  transition: all 0.2s ease;
}

.image-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.image-item.selected {
  border-color: #4caf50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.5);
}

.download-progress {
  margin-bottom: 1rem;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background-color: #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 0.5rem;
}

.progress-fill {
  height: 100%;
  background-color: #4caf50;
  transition: width 0.3s ease;
}
</style>